package com.ease.web.httpcomponent;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

public class HttpComponentTemplate {

	private static final transient Log log = LogFactory.getLog(HttpComponentTemplate.class);

	private HttpClient httpClient = new DefaultHttpClient();

	{
		httpClient = new DefaultHttpClient();

		// CookieSpecFactory csf = new CookieSpecFactory() {
		// public CookieSpec newInstance(HttpParams params) {
		// return new BrowserCompatSpec() {
		// @Override
		// public void validate(Cookie cookie, CookieOrigin origin)
		// throws MalformedCookieException {
		// // Oh, I am easy
		// }
		// };
		// }
		// };

		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
		// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, "easy");
		httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);

		// httpClient.getParams().ge.getCookieSpecs().register("easy", csf);
		// httpClient.getParams().setParameter( ClientPNames.COOKIE_POLICY, "easy");

	}

	public <T> T get(String url, ResponseHandler<T> responseHandler) {

		// //获得登陆后的 Cookie
		// Cookie[] cookies=httpClient.getState().getCookies();
		// String tmpcookies= "";
		// for(Cookie c:cookies){
		// tmpcookies += c.toString()+";";
		// }
		//
		// HttpState httpState = new HttpState();
		// Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff",
		// "/", null, false);
		//
		// httpState.addCookie(mycookie);
		// httpClient. .setState(httpState);

		T response = null;
		try {
			HttpGet httpGet = new HttpGet(url);

			response = httpClient.execute(httpGet, responseHandler);
		} catch (Exception e) {
			log.error("url=" + url, e);
		} finally {
			if (null != httpClient) {
				// httpClient.getConnectionManager().shutdown();
			}
		}
		return response;
	}

	public String getString(String url) {
		return get(url, new BasicResponseHandler());
	}

	public byte[] getByte(String url) {
		return get(url, new ByteResponseHandler());
	}

	public String postString(HttpPostCallback<String> httpPostCallback) {

		String url = httpPostCallback.getUri();

		String responseString = null;

		try {
			HttpPost httpPost = new HttpPost(url);

			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			httpPostCallback.setParameters(parameters);
			// parameters.add(new BasicNameValuePair("xmlmsg", request));

			HttpEntity httpEntity = new UrlEncodedFormEntity(parameters);// ,HTTP.UTF_8);
			httpPost.setEntity(httpEntity);

			HttpResponse response = httpClient.execute(httpPost);

			responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 处理乱码，对取得的result字符串作下转换，
			// result=new String(result.getBytes("ISO-8859-1"),"UTF-8") ;
			responseString = URLDecoder.decode(responseString, "UTF-8");
		} catch (Exception e) {
			if (null != httpClient) {
				// httpClient.getConnectionManager().shutdown();
			}
		}
		return responseString;
	}

}
